#include "mem_stack.h"

void k_mem_stack_init(mem_stack_kt* pStk, char* bottom, char* top)
{
    pStk->bottom   = (word_kt )bottom;
    pStk->top      = (word_kt )top;
    pStk->pCtrlBlk = (word_kt*)( ((word_kt)bottom+sizeof(word_kt)-1) & (~(sizeof(word_kt)-1)) );
    pStk->pMemBlk  = (word_kt )top;
    pStk->align = 8;
}


void* k_mem_stack_malloc(mem_stack_kt* pStk, word_kt size)
{
    word_kt a, b;

    a = (word_kt)(pStk->pCtrlBlk+1);
    b = (pStk->pMemBlk-size)&(~(pStk->align-1));

    if(a<=b)
    {
        *(pStk->pCtrlBlk) = pStk->pMemBlk;
        pStk->pCtrlBlk = (word_kt*)a;
        pStk->pMemBlk = b;
        return (void*)b;
    }

    return NULL;
}

bool_kt k_mem_stack_free(mem_stack_kt* pStk, void* addr)
{
    if( (word_kt)(pStk->pCtrlBlk-1) >= pStk->bottom && (word_kt)addr==pStk->pMemBlk)
    {
        pStk->pCtrlBlk--;
        pStk->pMemBlk = *(pStk->pCtrlBlk);
    }

    return FALSE;
}


